﻿using System;
using System.ComponentModel;
using Lwllm.ArcengineProxy.Common;
using Lwllm.ArcengineProxy.Core.Models;

namespace Lwllm.ArcengineProxy.Core.Annotations
{
    public class FieldNameAttribute : Attribute
    {
        public string Name { get; set; }

        public FieldNameAttribute(string name)
        {
            Name = name;
        }

        public static string GetFieldName<T>(string fieldName) where T : BaseEntity
        {
            var nameAttribute = TypeDescriptor.GetProperties(typeof(T))[fieldName].Attributes[typeof(FieldNameAttribute)];
            if (nameAttribute != null)
            {
                fieldName = ((FieldNameAttribute)nameAttribute).Name;
            }
            return fieldName;
        }

        public static void AddDescriptor(Type type, string propertyName, string fieldName)
        {
            //动态添加注解
            var ctd = new PropertyOverridingTypeDescriptor(
                TypeDescriptor.GetProvider(type).GetTypeDescriptor(type));
            var pd = TypeDescriptor.GetProperties(type)[propertyName];
            if (pd != null)
            {
                var newPd = TypeDescriptor.CreateProperty(
                    type,
                    pd,
                    new FieldNameAttribute(fieldName)
                );
                ctd.OverrideProperty(newPd);
            }
            TypeDescriptor.AddProvider(new TypeDescriptorOverridingProvider(ctd), type);

            //            //给fid加注解
            //            var fidFieldName = featureClassProxy.FeatrueClass.OIDFieldName;
            //            var ctd = new PropertyOverridingTypeDescriptor(
            //                TypeDescriptor.GetProvider(this.GetType()).GetTypeDescriptor(this.GetType()));
            //            var pd = TypeDescriptor.GetProperties(this.GetType())["Fid"];
            //            if (pd != null)
            //            {
            //                var newPd = TypeDescriptor.CreateProperty(
            //                    GetType(),
            //                    pd,
            //                    new FieldNameAttribute(fidFieldName)
            //                );
            //                ctd.OverrideProperty(newPd);
            //            }
            //            TypeDescriptor.AddProvider(new TypeDescriptorOverridingProvider(ctd), this.GetType());
        }
    }
}
